<?php

namespace app\api\controller;

use app\api\model\product\Car as CarModel;
use app\api\model\product\VinLog;
use app\common\library\easywechat\AppMp;
use app\common\model\product\CarQueryLog;
use app\common\model\product\Category;
use app\common\model\product\Product as ProductModel;
use lib\Liyang;
use think\facade\Log;
use app\JjjController;
use app\common\model\user\User as UserModel;

class Wechat extends JjjController
{
    public function index()
    {
        //获取微信消息

        // 微信登录 获取session_key
        $app = AppMp::getApp(10001);
        $server = $app->getServer();
        // return $server->serve();
        $message = $server->getRequestMessage(); // 原始消息
        Log::write($message,'原始消息');
        $server->with(function($message, \Closure $next) {
            switch ($message['MsgType']) {
                case 'event': //事件消息
                    $event = $message['Event'];
                    switch ($event) {
                        case 'subscribe'://添加关注
                            return '';
                        case 'unsubscribe'://取消关注
                            return '';
                        case 'LOCATION'://获取地理位置
                            return '';
                        case 'VIEW': //跳转链接,eventkey为链接
                            return '';
                        case 'SCAN': //扫码
                            return '';
                        case 'CLICK': //点击
                            if($message['EventKey']){
                                return "合作:13837113377 王经理\r        19937871444 王经理\r服务:13460829444 李    工";
                            }
                        default:
                            break;
                    }
                case 'text': //文字消息
                    $content = $message['Content'];
                    if(strlen($content) == 17){
                        //判断是否为会员
                        $user = UserModel::where('mpopen_id',$message['FromUserName'])->find();
                        if(!$user){
                            return '请联系供货商审核通过后方可查询';
                        }

                        list($result,$msg) = CarQueryLog::checkSearch($user->user_id);
                        if(!$result) return '您的查询次数已用完，请联系供货商';

                        return $this->getCarInfo($content,$user->user_id);
                    }
                case 'image': //图片消息
                    //判断是否为会员
                    $user = UserModel::where('mpopen_id',$message['FromUserName'])->find();
                    if(!$user){
                        return '请联系供货商审核通过后方可查询';
                    }

                    list($result,$msg) = CarQueryLog::checkSearch($user->user_id);
                    if(!$result) return '您的查询次数已用完，请联系供货商';

                    $picUrl = $message['PicUrl'];
                    $imageData = $this->picUrlToBase64($picUrl);
                    if($imageData !== false){
                        $ret = Liyang::getvinbyocr($imageData);
                        if($ret['code'] != 1 || $ret['data']['Info']['success'] == 'false'){
                            return '识别失败！';
                        }else{
                            return $this->getCarInfo($ret['data']['Result'],$user->user_id);
                        }
                    }

                case 'voice': //语音消息
                case 'video': //视频消息
                case 'location': //坐标消息
                case 'link': //链接消息
                default: //其它消息
            }
        });

        return $server->serve();

    }
    
     public function menu()
    {
        $app = AppMp::getApp(10001);
        $client = $app->getClient();
        $response = $client->postJson('/cgi-bin/menu/create', [
            "button"=>[
                [
                    'type' => 'view',
                    'name' => '产品查询',
                    'url' => 'https://che.xinyaoan.com/h5/?app_id=10001',
                ],
                [
                    'type' => 'click',
                    'name' => '关于我们',
                    'key' => 'about',
                ]
            ]
        ]);
        return $response;
    }


    /**
     * 将网络图片URL转换为base64编码
     * @param string $picUrl 图片网络URL
     * @return string|false 成功返回base64字符串，失败返回false
     */
    protected function picUrlToBase64($picUrl) {
        // 初始化curl
        $ch = curl_init();
        // 设置curl参数
        curl_setopt($ch, CURLOPT_URL, $picUrl); // 目标URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 结果返回为字符串
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略SSL证书验证（避免HTTPS链接报错）
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 超时时间10秒

        // 执行请求，获取图片二进制内容
        $imageContent = curl_exec($ch);

        // 检查错误
        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        }
        curl_close($ch);

        // 转换为base64
        return base64_encode($imageContent);
    }


    protected function getCarInfo($vin,$user_id)
    {
        $vin_sub = substr($vin,0,11);
        $returnData =  VinLog::where('vin_sub',$vin_sub)->find();
        if (!$returnData) {
            $ret = Liyang::getPreciseCompressVin($vin);
            if($ret['code'] != 1){
                return '未查询到数据';
            }
            $returnData = $ret['data'];
            $returnData['app_id'] = 10001;
            $returnData['vin'] = $vin;
            $returnData['vin_sub'] = $vin_sub;
            VinLog::create($returnData);
        }
        $info = CarModel::whereIn('ly_pid',explode(';',$returnData['levelIds']))->find();
        if(empty($info)){
            return '未获取到车型';
        }
        //添加用户记录
        $data = [
            'type'=>1,
            'vin'=>$vin,
            'car_id'=>$info['id'],
            'user_id'=>$user_id,
            'app_id'=>10001,
            'create_time'=>time(),
        ];
        CarQueryLog::create($data);
        $return_str = "【车架号】\r".$vin."\r【车型】\r".$info['brand'].' '.$info['models'].' '.$info['yeartype']."款 \r";

        $product_str = $this->getGoods($info['id'],$vin);
        $return_str .= $product_str;
        return $return_str;
    }


    protected function getGoods($car_id,$vin)
    {

        $category_id_arr = ProductModel::where('is_delete', '=', 0)
            ->where('product_status', '=', 10)
            ->where('audit_status', '=', 10)
            ->where('FIND_IN_SET(:car_id, car_ids)',['car_id' => $car_id])
            ->where('app_id',10001)
            ->column('category_id');

        $product_list = ProductModel::where('is_delete', '=', 0)
            ->field('product_no,install_position,category_id')
            ->where('product_status', '=', 10)
            ->where('audit_status', '=', 10)
            ->where('FIND_IN_SET(:car_id, car_ids)',['car_id' => $car_id])
            ->where('app_id',10001)
            ->limit(15)
            ->select();

        $count = ProductModel::where('is_delete', '=', 0)
            ->where('product_status', '=', 10)
            ->where('audit_status', '=', 10)
            ->where('FIND_IN_SET(:car_id, car_ids)',['car_id' => $car_id])
            ->where('app_id',10001)
            ->count();


        $category_list = Category::where('status', '=', 1)
            ->field('category_id,name')
            ->whereIn('category_id',$category_id_arr)
            ->order('sort asc')
            ->select();

        // 2. 按分类分组并过滤空分类
        $categoryMap = [];
        foreach ($category_list as $category) {
            $cid = $category['category_id'];
            $categoryMap[$cid] = $category;
        }

        $groupedResult = [];
        foreach ($categoryMap as $cid => $category) {
            $groupedResult[$cid] = [
                'category_id' => $cid,
                'name' => $category['name'],
                'products' => []
            ];
        }

        foreach ($product_list as $product) {
            $productCid = $product['category_id'];
            if (isset($groupedResult[$productCid])) {
                $groupedResult[$productCid]['products'][] = $product;
            }
        }

        // 过滤掉没有商品的空分类（products为空的分类）
        $finalResult = array_values(array_filter($groupedResult, function($item) {
            return !empty($item['products']); // 仅保留有商品的分类
        }));


        // 3. 生成目标格式字符串
        $output = "[爱心]为您找到了以下适配商品[爱心] \r\n";
        $totalCategories = count($finalResult); // 用于控制分类间空行

        foreach ($finalResult as $index => $category) {
            // 拼接分类名称
            $output .= "【{$category['name']}】\r\n";

            // 拼接该分类下的商品
            foreach ($category['products'] as $product) {
                $productNo = $product['product_no'];
                $sellingPoint = $product['install_position'] ?? ''; // 处理可能的null值

                // 核心优化2：install_position为空时不显示括号
                if (!empty($sellingPoint)) {
                    $output .= "{$productNo}({$sellingPoint})\r\n";
                } else {
                    $output .= "{$productNo}\r\n";
                }
            }
        }

        if ($count > 15) {
            $output .= "❗<a href='https://che.xinyaoan.com/h5/pages/product/categoryNew?car_id={$car_id}&vin={$vin}'>该车产品较多，点此查询</a> \r\n";
        }
        $output .= "可以输入其他车架号继续查询\r也可以 <a href ='https://che.xinyaoan.com/h5/pages/product/categoryNew?car_id={$car_id}&vin={$vin}'>点击链接查看详情、图片</a >";

        return $output;
    }





}
